﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GypeLaunch
{
    public partial class ChooseProcessDialog : Form
    {
        public int ChosenProcess { get; private set; }

        public ChooseProcessDialog()
        {
            InitializeComponent();
            ChosenProcess = -1;
        }

        public void AddItem(string name)
        {
            listBox1.Items.Add(name);
        }

        private void choose()
        {
            ChosenProcess = listBox1.SelectedIndex;
            this.Close();

            string str = (string)listBox1.SelectedItem;
            if (str == null)
                return;

            ChosenProcess = int.Parse(str.Substring(0, str.IndexOf(' ')));
        }

        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            choose();
        }

        private void listBox1_KeyUp(object sender, KeyEventArgs e)
        {
            choose();
        }

        private void ChooseProcessDialog_Load(object sender, EventArgs e)
        {
            var processes = Process.GetProcesses();

            foreach (Process proc in processes)
            {
                try
                {
                    Win32.EnumProcessModules(proc.Id, delegate(Win32.ModuleEntry32 module)
                    {
                        if (Filter(proc.MainModule, module))
                        {
                            AddItem(String.Format("{0} - {1}", proc.Id, proc.ProcessName));
                            return true;
                        }
                        return false;
                    });
                }
                catch (Exception)
                {
                }
            }
        }

        private bool Filter(ProcessModule mainModule, Win32.ModuleEntry32 module)
        {
            var filename = mainModule.FileName.ToLower();

            bool ret = true;
            ret = ret && module.ModuleName.ToLower().Contains("d3d");
            ret = ret && !filename.Contains("c:\\windows\\");
            ret = ret && !filename.Contains("ati");
            ret = ret && !filename.Contains("firefox");
            ret = ret && !filename.Contains("devenv");
            ret = ret && !filename.Contains("skype");

            return ret;
        }
    }
}
